/*
 * Copyright (C) 2022 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.car.settings.applications.performance;

import android.content.Context;

import androidx.annotation.NonNull;

import com.android.settingslib.utils.ThreadUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Class used to get the disabled packages due to resource overuse.
 */
public class PerfImpactingAppsItemManager {

    private Context mContext;
    private final List<PerfImpactingAppsListener> mPerfImpactingAppsListeners;

    public PerfImpactingAppsItemManager(Context context) {
        mContext = context;
        mPerfImpactingAppsListeners = new ArrayList<>();
    }

    /**
     * Registers a listener that will be notified once the data is loaded.
     */
    public void addListener(@NonNull PerfImpactingAppsListener listener) {
        mPerfImpactingAppsListeners.add(listener);
    }

    /**
     * Starts fetching installed apps and counting the non-system apps
     */
    public void startLoading() {
        ThreadUtils.postOnBackgroundThread(() -> {
            int disabledPackagesCount = PerfImpactingAppsUtils.getDisabledPackages(mContext).size();
            for (PerfImpactingAppsListener listener : mPerfImpactingAppsListeners) {
                ThreadUtils.postOnMainThread(() -> listener
                        .onPerfImpactingAppsLoaded(disabledPackagesCount));
            }
        });
    }

    /**
     * Callback that is called once the performance-impacting apps are loaded.
     */
    public interface PerfImpactingAppsListener {
        /**
         * Called when the apps are successfully loaded from secure settings strings and
         * PackageManager.
         */
        void onPerfImpactingAppsLoaded(int disabledPackagesCount);
    }
}
